package com.example.weight.householdWaste;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.model.FaultModel;
import com.example.weight.util.Utility;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class FaultRepairActivity extends AppCompatActivity {

    private String name, factory;

    private EditText systemName, facilityName, step,
            occurDate, occurTime, faultDescription, personInCharge;
//            occurReason, repairMethod, provider, repairDate, repairStartTime,
//            repairEndDate, repairEndTime, repairPerson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fault_repair);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        TitleBar titleBar = findViewById(R.id.fault_repair_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        systemName = findViewById(R.id.fault_repair_system_name);
        facilityName = findViewById(R.id.fault_repair_facility_name);
        step = findViewById(R.id.fault_repair_step);
        occurDate = findViewById(R.id.fault_repair_fault_occur_date);
        occurTime = findViewById(R.id.fault_repair_fault_occur_time);
        faultDescription = findViewById(R.id.fault_repair_fault_situation);
//        occurReason = findViewById(R.id.fault_repair_fault_reason);
//        repairMethod = findViewById(R.id.fault_repair_fault_repair_method);
//        provider = findViewById(R.id.fault_repair_fault_repair_method_person);
//        repairDate = findViewById(R.id.fault_repair_fault_repair_date);
//        repairStartTime = findViewById(R.id.fault_repair_fault_repair_start_time);
//        repairEndDate = findViewById(R.id.fault_repair_repair_end_date);
//        repairEndTime = findViewById(R.id.fault_repair_fault_repair_end_time);
//        repairPerson = findViewById(R.id.fault_repair_fault_repair_person);
        personInCharge = findViewById(R.id.fault_repair_personInCharge);

//        RequestQueue queue = Volley.newRequestQueue(this);
//        String url = Config.url + "/shlj/troubleshooting/getlast";
//        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//                        try {
//                            JSONObject jsonObject = new JSONObject(response);
//                            if (!jsonObject.isNull("data")) {
//                                JSONObject data = jsonObject.getJSONObject("data");
//                                systemName.setText(data.getString("systemName"));
//                                facilityName.setText(data.getString("equipmentName"));
//                                step.setText(data.getString("stage"));
//                                String timeOfFailure = data.getString("timeOfFailure");
//                                occurDate.setText(timeOfFailure.split(" ")[0]);
//                                occurTime.setText(timeOfFailure.split(" ")[1]);
//                                faultDescription.setText(data.getString("faultDescription"));
//                                occurReason.setText(data.getString("faultReasion"));
//                                repairMethod.setText(data.getString("faultRepairMethod"));
//                                provider.setText(data.getString("methodProposer"));
//                                String repairStart = data.getString("repairStartTime");
//                                repairDate.setText(repairStart.split(" ")[0]);
//                                repairStartTime.setText(repairStart.split(" ")[1]);
//                                String repairEnd = data.getString("repairEndTime");
//                                repairEndDate.setText(repairEnd.split(" ")[0]);
//                                repairEndTime.setText(repairEnd.split(" ")[1]);
//                                repairPerson.setText(data.getString("repairPerson"));
//                                personInCharge.setText(data.getString("personInCharge"));
//                                Toast.makeText(FaultRepairActivity.this,
//                                        "今日已填写此表", Toast.LENGTH_SHORT).show();
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                Toast.makeText(FaultRepairActivity.this,
//                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
//            }
//        });
//        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
//                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//        queue.add(stringRequest);

        occurDate.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Calendar calendar = Calendar.getInstance();
                final int YEAR = calendar.get(Calendar.YEAR);
                final int MONTH = calendar.get(Calendar.MONTH);
                final int DAY = calendar.get(Calendar.DAY_OF_MONTH);

                @SuppressLint({"SetTextI18n", "ResourceType"})
                DatePickerDialog datePickerDialog = new DatePickerDialog(FaultRepairActivity.this, 2,
                        (view1, year, month, day) ->
                                occurDate.setText(year + "/"
                                        + ((month + 1) < 10 ? "0" + (month + 1) : (month + 1)) + "/"
                                        + ((day < 10) ? "0" + day : day)),
                        YEAR,
                        MONTH,
                        DAY);
                datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        occurDate.clearFocus();
                    }
                });
                datePickerDialog.show();
            }
        });
        occurTime.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Calendar calendar = Calendar.getInstance();
                int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
                int MINUTE = calendar.get(Calendar.MINUTE);

                @SuppressLint({"DefaultLocale", "SetTextI18n"})
                TimePickerDialog timePickerDialog = new TimePickerDialog(FaultRepairActivity.this, 2,
                        (view1, hourOfDay, minute) ->
                                occurTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                        ,HOUR
                        ,MINUTE
                        ,true);
                timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        occurTime.clearFocus();
                    }
                });
                timePickerDialog.show();
            }
        });
    }

    @SuppressLint({"SetTextI18n", "ResourceType"})
    public void selectOccurDate(View view) {
        Calendar calendar = Calendar.getInstance();
        final int YEAR = calendar.get(Calendar.YEAR);
        final int MONTH = calendar.get(Calendar.MONTH);
        final int DAY = calendar.get(Calendar.DAY_OF_MONTH);

        new DatePickerDialog(this, 2, (view1, year, month, day) ->
                occurDate.setText(year + "/"
                        + ((month + 1) < 10 ? "0" + (month + 1) : (month + 1)) + "/"
                        + ((day < 10) ? "0" + day : day)),
                YEAR,
                MONTH,
                DAY).show();
    }

    @SuppressLint({"DefaultLocale", "SetTextI18n"})
    public void selectOccurTime(View view) {
        Calendar calendar = Calendar.getInstance();
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);

        new TimePickerDialog(this, 2, (view1, hourOfDay, minute) ->
                occurTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                ,HOUR
                ,MINUTE
                ,true).show();
    }
    public void save(View view) {
        if (systemName.getText().toString().equals("")) {
            Toast.makeText(this, "请填写系统名称", Toast.LENGTH_SHORT).show();
            return;
        }
        if (facilityName.getText().toString().equals("")) {
            Toast.makeText(this, "请填写设备名称", Toast.LENGTH_SHORT).show();
            return;
        }
        if (step.getText().toString().equals("")) {
            Toast.makeText(this, "请填写阶段", Toast.LENGTH_SHORT).show();
            return;
        }
        if (occurDate.getText().toString().equals("")) {
            Toast.makeText(this, "请填写故障发生日期", Toast.LENGTH_SHORT).show();
            return;
        }
        if (occurTime.getText().toString().equals("")) {
            Toast.makeText(this, "请填写故障发生时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (faultDescription.getText().toString().equals("")) {
            Toast.makeText(this, "请填写故障描述", Toast.LENGTH_SHORT).show();
            return;
        }
        if (personInCharge.getText().toString().equals("")) {
            Toast.makeText(this, "请填写负责人", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
            .setTitle("确定保存吗？")
            .setCancelable(false)
            .setNegativeButton("取消", ((dialog, which) ->
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
            .setPositiveButton("确定", (dialog, which) -> {

                // 提交表单
                RequestQueue queue = Volley.newRequestQueue(this);
                String addUrl = Config.url + "/shlj/troubleshooting/addFrontPart";
                StringRequest addRequest = new StringRequest(Request.Method.POST, addUrl,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String code = jsonObject.getString("code");
//                                    systemName.setText("");
//                                    facilityName.setText("");
//                                    step.setText("");
//                                    occurDate.setText("");
//                                    occurTime.setText("");
//                                    faultDescription.setText("");
//                                    occurReason.setText("");
//                                    repairMethod.setText("");
//                                    provider.setText("");
//                                    repairDate.setText("");
//                                    repairStartTime.setText("");
//                                    repairEndTime.setText("");
//                                    repairPerson.setText("");
//                                    personInCharge.setText("");

                                    if (code.startsWith("2"))
                                        Toast.makeText(FaultRepairActivity.this,
                                                "保存成功", Toast.LENGTH_SHORT).show();
                                    else
                                        Toast.makeText(FaultRepairActivity.this,
                                                "保存失败", Toast.LENGTH_SHORT).show();

                                    String getListUrl = Config.url + "/shlj/troubleshooting/getList" + "?factory=" + factory;
                                    StringRequest getListRequest = new StringRequest(Request.Method.GET, getListUrl,
                                            new Response.Listener<String>() {
                                                public void onResponse(String response) {
                                                    try {
                                                        JSONObject jsonObject = new JSONObject(response);
                                                        if (!jsonObject.isNull("data")) {
                                                            String listString = "";
                                                            JSONArray data = jsonObject.getJSONArray("data");
                                                            for (int i = 0; i < data.length(); i++) {
                                                                JSONObject item = data.getJSONObject(i);
                                                                String id = item.getString("id");
                                                                String system = item.getString("systemName");
                                                                String equipment = item.getString("equipmentName");
                                                                String occurTime = item.getString("timeOfFailure");
                                                                String step = item.getString("stage");
                                                                String description = item.getString("faultDescription");
                                                                String personInCharge = item.getString("personInCharge");
                                                                FaultModel faultModel = new FaultModel(id, system, equipment, occurTime, step, description, personInCharge);
                                                                listString = listString.concat(faultModel.toSplitWithSpace());
                                                                if (i < data.length()-1)
                                                                    listString = listString.concat(",");
                                                            }

                                                            Intent intent = new Intent();
                                                            intent.putExtra("list", listString);
                                                            intent.putExtra("needRefresh", true);
                                                            intent.putExtra("factory", factory);
                                                            setResult(RESULT_OK, intent);

                                                            finish();
                                                        }
                                                    } catch (JSONException e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            }, new Response.ErrorListener() {
                                        @Override
                                        public void onErrorResponse(VolleyError error) {}
                                    });
                                    getListRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                                    queue.add(getListRequest);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(FaultRepairActivity.this,
                                "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> map=new HashMap<>();
                        map.put("personInCharge", personInCharge.getText().toString());
                        map.put("systemName", systemName.getText().toString());
                        map.put("equipmentName", facilityName.getText().toString());
                        map.put("stage", step.getText().toString());
                        map.put("recordingPerson", name);
                        map.put("timeOfFailure", occurDate.getText().toString()+" "+occurTime.getText().toString());
                        map.put("faultDescription", faultDescription.getText().toString());
                        map.put("factory", factory);
//                        map.put("faultReasion", occurReason.getText().toString());
//                        map.put("faultRepairMethod", repairMethod.getText().toString());
//                        map.put("repairStartTime", repairDate.getText().toString()+" "+repairStartTime.getText().toString());
//                        map.put("repairEndTime", repairEndDate.getText().toString()+" "+repairEndTime.getText().toString());
//                        map.put("repairPerson", repairPerson.getText().toString());
//                        map.put("methodProposer", provider.getText().toString());
                        return map;
                    }
                };
                addRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                queue.add(addRequest);
            })
            .show();
    }
}
